package kassiopeia.agent.seda.stage;

import kassiopeia.agent.seda.config.State;
import kassiopeia.agent.seda.event.EventQueue;
import kassiopeia.plugin.DataProviderPlugin;
import kassiopeia.plugin.Plugin;
import kassiopeia.plugin.PluginException;
import kassiopeia.plugin.ProcessorPlugin;
import org.apache.log4j.Logger;

public class Stage implements Runnable {

    private final Logger log = Logger.getLogger(Stage.class);
    private final EventQueue eventQueue;
    private final String pluginInstanceId;
    private final Controller controller;
    private final Plugin plugin;
    private State state;

    public Stage(Plugin plugin, EventQueue eventQueue, Controller controller) throws PluginException {
        this.pluginInstanceId = plugin.getContext().getPluginInstanceId();
        this.eventQueue = eventQueue;
        this.controller = controller;
        this.plugin = plugin;
        this.state = State.CREATED;
    }

    @Override
    public void run() {
        log.info("Starting plugin: " + pluginInstanceId);
        state = State.RUNNING;

        plugin.beforeTask();

        if (plugin instanceof DataProviderPlugin) {
            new DataProviderExecutor(plugin).execute();
        }

        if (plugin instanceof ProcessorPlugin) {
            new ProcessorExecutor(this).execute();
        }

        plugin.afterTask();

        state = State.STOPPED;
        log.info("Plugin " + pluginInstanceId + " stopped");
    }

    public void stop() {
        state = State.TERMINATING;
    }

    public EventQueue getEventQueue() {
        return this.eventQueue;
    }

    public Plugin getPlugin() {
        return this.plugin;
    }

    public State getState() {
        return this.state;
    }

    public Controller getController() {
        return this.controller;
    }
}
